package thomas.studio.spring.security.ldap.service;

import java.util.List;

import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.ContextMapper;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;


@Service
public class LdapService {
	
	@Autowired
	private LdapTemplate ldapTemplate;
	
	private final static Log LOG = LogFactory.getLog(LdapService.class);
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public User getUserById(String uid) {
	    String filter = "(&(objectclass=inetOrgPerson)(uid=" + uid + "))";
	    List<User> list = ldapTemplate.search("ou=people", filter, new AttributesMapper() {
	        @Override
			public Object mapFromAttributes(Attributes attributes) throws NamingException, javax.naming.NamingException {
			    User user = new User();
		 
		            Attribute a = attributes.get("cn");
		           // if (a != null) user.setRealname((String)a.get());
		 
		            a = attributes.get("uid");
		            //if (a != null) user.setUsername((String)a.get());
		 
		            return user;
			}

	    });
	    if (list.isEmpty()) return null;
	    return list.get(0);
	}
	
	
/*	public void getUsersById(String uid) {
		this.ldapTemplate.searchForObject("dc=thomas-studio,dc=com", 
				"(&(objectclass=inetOrgPerson)(uid=" + uid + "))", 
				new ContextMapper<User>() {
					@Override
					public User mapFromContext(Object ctx) throws javax.naming.NamingException {
						DirContextOperations context = (DirContextOperations) ctx;
						String userId = context.getStringAttribute("uid");
						LOG.info("uid: " + userId);
						return null;
					}
				});
	}*/

}
